<template>
  <view class="buy-ticket-view p-page">
    <view class="page-box TrainItem lg p-base">
      <view class="text-primary text-center"
        >{{ $u.dayjs(date).format("MM月DD日") }}&ensp;{{
          $u.dayjs(date).isToday() ? "今天" : $u.timeFormat(date, "[周]dd")
        }}</view
      >
      <u-row :gutter="12" class="mt-base py-llg">
        <u-col :span="4">
          <view class="Time">{{ fromTime | timeFormat("HH:mm") }}</view>
          <view class="Station">{{ from }}</view>
        </u-col>
        <u-col :span="4">
          <view class="text-center" :style="{ fontSize: '14px' }">
            <view>{{ trainNo }}</view>
            <u-line></u-line>
            <view>{{ fromTime | timeDiff(toTime) }}</view>
          </view>
        </u-col>
        <u-col :span="4">
          <view class="Time text-end">{{ toTime | timeFormat("HH:mm") }}</view>
          <view class="Station text-end">{{ to }}</view>
        </u-col>
      </u-row>
    </view>

    <view class="mt-base p-base bg-white rounded-sm">
      <view>
        <u-text text="乘车人" :size="18" :bold="true"></u-text>
      </view>
      <view class="my-base">
        <u-line></u-line>
      </view>
      <view>
        <u-text :text="$store.state.auth.name"></u-text>
      </view>
      <view class="mt-sm">
        <u-text
          type="info"
          :size="12"
          :text="$store.state.auth.idCardNo | hideIdCardNo"
        ></u-text>
      </view>
    </view>

    <view class="mt-base" :style="{ fontSize: '13px' }">
      <text class="text-info">确定支付表示已阅读并同意</text
      ><text class="text-primary"
        >《国铁集团铁路旅客运输规程》《服务条款》</text
      >
    </view>

    <view class="mt-llg">
      <u-button
        type="primary"
        :custom-style="{ borderRadius: `var(--rounded-sm)` }"
        @tap="handlePayment"
        >确定支付</u-button
      >
    </view>

    <view
      class="relative rounded-sm"
      :style="{
        '--title-move-y': '-13px',
        marginTop: 'calc(var(--space-llg) - var(--title-move-y))',
        border: '1px dashed #ceccca',
      }"
    >
      <view
        class="absolute"
        :style="{
          backgroundColor: 'var(--color-background)',
          marginLeft: '-2px',
          paddingLeft: '2px',
          height: '26px',
          top: 'var(--title-move-y)',
          left: '0',
        }"
      >
        <view class="u-flex-y-center" :style="{ fontSize: '15px' }">
          <u-icon name="info-circle-fill" color="var(--color-primary)"></u-icon>
          <text class="ms-sm fw-bold">温馨提示：</text>
        </view>
      </view>
      <view class="p-sm pt-llg text-info" :style="{ fontSize: '13px' }">
        <!--
        <view
          >1.一天内3次申请车票成功后取消订单（包含无座车票或不符合选铺需求车票时取消5次计为取消1次），当日将不能在Mini-12306继续购票。</view
        >
        -->
        <view
          >如因运力原因或其他不可控因素导致列车调度调整时，当前车型可能会发生变动。</view
        >
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from "vuex";
import apiOrders from "@/api/orders.js";
import apiTickets from "@/api/tickets";

export default {
  data() {
    return {
      trainNo: "",
      from: "",
      fromTime: "",
      to: "",
      toTime: "",
      date: "",
      passengers: [],
    };
  },
  computed: {
    ...mapState({ auth: "auth" }),
  },
  onLoad(query) {
    if (!this.auth.id) {
      uni.navigateTo({ url: "/pages/LoginView/LoginView" });
      return;
    }

    /**
     * 默认添加当前登录用户作为乘车人
     */
    this.passengers.push({
      id: this.auth.id,
      name: this.auth.name,
      idCardNo: this.auth.idCardNo,
    });

    const { train_no, from, from_time, to, to_time, date } = query;

    this.trainNo = decodeURIComponent(train_no);
    this.from = decodeURIComponent(from);
    this.fromTime = decodeURIComponent(from_time);
    this.to = decodeURIComponent(to);
    this.toTime = decodeURIComponent(to_time);
    this.date = this.$u.dayjs(decodeURIComponent(date)).format();
  },
  methods: {
    handlePayment() {
      /**
       * 这里将订单确认与支付合并到了一个页面，
       * 实际上应该确认订单后跳转到支付页面
       *
       * 订单层其实是预留了实现一个订单多张车票（乘车人）的情况
       */
      uni.showLoading({ title: "正在确认订单", mask: true });
      apiOrders
        .add({
          tickets: this.passengers.map((pax) => ({
            trainNo: this.trainNo,
            from: this.from,
            to: this.to,
            date: this.date,
            passengerId: pax.id,
          })),
        })
        .then((apiOrdersAddRes) => {
          uni.hideLoading();

          /**
           * 支付订单
           */
          uni.showLoading({ title: "正在支付", mask: true });

          apiOrders
            .payment({
              orderNo: apiOrdersAddRes.data.orderNo,
            })
            .then(() => {
              uni.hideLoading();

              const wait = 1000;
              uni.showToast({
                title: "支付成功",
                mask: true,
                duration: wait,
              });

              setTimeout(() => {
                /**
                 * 查询支付结果
                 */
                uni.showLoading({ title: "查询订单状态", mask: true });

                apiOrders
                  .queryPayment({
                    orderNo: apiOrdersAddRes.data.orderNo,
                  })
                  .then(() => {
                    uni.hideLoading();
                    const wait = 1000;
                    uni.showToast({
                      title: "订单已支付",
                      mask: true,
                      duration: wait,
                    });
                    setTimeout(() => {
                      uni.switchTab({
                        url: "/pages/MyTicketsView/MyTicketsView",
                      });
                    }, wait);
                  })
                  .catch(() => uni.hideLoading());
              }, wait);
            })
            .catch(() => uni.hideLoading());
        })
        .catch(() => uni.hideLoading());
    },
  },
};
</script>

<style scoped>
.buy-ticket-view {
  background: linear-gradient(
    var(--color-app-blue) 0 40px,
    80px,
    var(--color-background) 120px
  );
}
</style>
